package com.tjetc.utils;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @Author: itda
 * @Date: 2024/5/12 21:09
 * @Description: 发邮件工具类
 */
public class EmailUtil {
    public static void sendEmail(String to, String subject, String content) {
        // 配置邮件服务器信息
        Properties properties = new Properties();

        properties.put("mail.smtp.host", "smtp.qq.com"); // 邮件服务器地址
        properties.put("mail.smtp.port", "587"); // 邮件服务器端口
        properties.put("mail.smtp.auth", "true"); // 开启认证
        properties.put("mail.smtp.starttls.enable", "true"); // 开启TLS加密

        // 邮箱账户信息
        final String username = "2226217200@qq.com"; // 发件人邮箱
        final String autuCode = "ixmqivqnzheqdjdi";
        //final String password = "ixmqivqnzheqdjdi"; // 发件人邮箱密码

        // 创建邮件会话
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, autuCode);
            }
        });

        try {
            // 创建邮件消息
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
            message.setSubject(subject);
            message.setText(content);

            // 发送邮件
            Transport.send(message);
            System.out.println("邮件发送成功");
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
